package com.romadan.utils;

import java.util.LinkedHashMap;
import java.util.Map;

public final class UnitConversions {
	private final static double PI = 3.14159265;
	private static LinkedHashMap<String, Double> prefixes;
	
	static {
		prefixes = new LinkedHashMap<String, Double>();
		prefixes.put("femto", new Double(1E-15));
		prefixes.put("piko", new Double(1E-12));
		prefixes.put("nano", new Double(1E-9));
		prefixes.put("micro", new Double(1E-6));
		prefixes.put("milli", new Double(1E-3));
		prefixes.put("kilo", new Double(1E3));
		prefixes.put("mega", new Double(1E6));
		prefixes.put("giga", new Double(1E9));
		prefixes.put("tera", new Double(1E12));
	}
	
	public static double frequencyLinearToCyclic(double linFreq, String prefix) {
		double cycFreq = 2*PI*linFreq;
		if (prefix!=null && prefix.length()!=0) {
			cycFreq *= prefixes.get(prefix);
		}
		
		return cycFreq;
	}
	
	public static double frequencyLinearToCyclic(double linFreq, String fromPrefix, String toPrefix) {
		linFreq = convert(linFreq, fromPrefix, toPrefix);
		double cycFreq = 2*PI*linFreq;
		
		return cycFreq;
	}
	
	public static double frequencyLinearToCyclic(String linFreq, String prefix) {
		double cycFreq = 2*PI*Double.parseDouble(linFreq);
		if (prefix!=null && prefix.length()!=0) {
			cycFreq *= prefixes.get(prefix);
		}
		
		return cycFreq;
	}
	
	public static double convert(double value, String fromPrefix, String toPrefix) {
		double freq = value;
		if (fromPrefix!=null && fromPrefix.length()!=0)
			freq *= prefixes.get(fromPrefix);
		if (toPrefix!=null && toPrefix.length()!=0)
			freq /= prefixes.get(toPrefix);
		
		return freq;
	}
	
	public static String convert(String value, String fromPrefix, String toPrefix) {
		double freq = convert(Double.parseDouble(value), fromPrefix, toPrefix);
		return String.valueOf(freq);
	}
	
	public static String freqToString(double freq, String fromPrefix, String toPrefix, String unit) {
		double value = convert(freq, fromPrefix, toPrefix);
		String strFreq = value + " " + toPrefix + unit;
		
		return strFreq;
	}
	
	public static Map<String, Double> getUnits() {
		return prefixes;
	}
}
